import './public-path'
// with polyfills
import 'core-js/stable'
import 'regenerator-runtime/runtime'

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
import routes from './router'
import store from './store/'
import { VueAxios } from './utils/request'

import { Collapse, FormModel } from 'ant-design-vue'

// mock
// WARNING: `mockjs` NOT SUPPORT `IE` PLEASE DO NOT USE IN `production` ENV.
// import './mock'

import { Initializer as oldBootstrap } from './core/bootstrap'
import './core/lazy_use'
import { beforeRouter, afterRouter } from './permission' // permission control
import './utils/filter' // global filter
import './components/global.less'
import { Dialog } from '@/components'

import * as Cesium from 'cesium'
import 'cesium/Build/Cesium/Widgets/widgets.css'
Vue.config.productionTip = false

Vue.prototype.Cesium = Cesium

// mount axios Vue.$http and this.$http
Vue.use(VueAxios)
Vue.use(Dialog)

// new Vue({
//   router,
//   store,
//   created: bootstrap,
//   render: (h) => h(App)
// }).$mount('#app')

Vue.component(Collapse.name, Collapse)
Vue.component(Collapse.Panel.name, Collapse.Panel)
Vue.component(FormModel.name, FormModel)
Vue.component(FormModel.Item.name, FormModel.Item)

let router = null
let instance = null

function render(props = {}) {
  const { container, routerBase } = props
  router = new VueRouter({
    base: window.__POWERED_BY_QIANKUN__ ? routerBase : process.env.BASE_URL,
    // base: window.__POWERED_BY_QIANKUN__ ? '/vue' : '/',
    mode: 'history',
    scrollBehavior: () => ({ y: 0 }),
    routes
  })
  beforeRouter(router)
  afterRouter(router)
  instance = new Vue({
    router,
    store,
    created: oldBootstrap(),
    render: (h) => h(App)
  }).$mount(container ? container.querySelector('#app') : '#app')
}
if (!window.__POWERED_BY_QIANKUN__) {
  render()
}

export async function bootstrap() {
  console.log('[vue] vue app bootstraped')
}

export async function mount(props) {
  console.log('[vue] props from main framework', props)
  render(props)
  const { data } = props
  props.onGlobalStateChange((state, prevState) => {
    // state: 变更后的状态; prev 变更前的状态
    console.log('通信状态发生改变：', state, prevState)
    // 这里监听到globalToken变化再更新store
    // store.commit('setToken', '******')
    store.commit('SET_TOKEN', data.token)
    store.commit('SET_INFO', state)
  }, true)
}

export async function unmount() {
  instance.$destroy()
  instance = null
  router = null
}
